# 作者: YYJ
# 2025年07月17日12时55分25秒
# 2486249622@qq.com
import re
from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR


def service_client(client_socket):
    request = client_socket.recv(4096).decode('utf-8')
    print(request)
    request_lines = request.splitlines()
    print("")
    print(">" * 20)
    print(request_lines)
    if request_lines:
        file_name = ""
        ret = re.match(r"[^/]+(/[^ ] *)", request_lines[0])
        if ret:
            file_name = ret.group(1)
            print("*" * 50, file_name)
            if file_name == "/":
                file_name = "index.html"

        try:
            f = open("./html" + file_name, "rb")
        except:
            response = "HTTP/1.1 404 NOT FOUND\r\n"
            response += "\r\n"
            response += "----file not found----"
            client_socket.send(response.encode("utf-8"))
        else:
            html_content = f.read()
            f.close()
            response = "HTTP/1.1 200 OK\r\n"
            response += "\r\n"
            client_socket.send(response.encode("utf-8"))
            client_socket.send(html_content)

    client_socket.close()

def main():
    tcp_server = socket(AF_INET, SOCK_STREAM)
    tcp_server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    tcp_server.bind(('', 7890))
    tcp_server.listen(128)
    while True:
        client_socket, client_addr = tcp_server.accept()
        service_client(client_socket)
        
    tcp_server.close()
    